package com.ypx.ec.product.service.impl;



import com.alibaba.fastjson.TypeReference;
import com.ypx.ec.common.constant.ProductConstant;
import com.ypx.ec.common.to.SkuReductionTo;
import com.ypx.ec.common.to.SpuBoundsTo;
import com.ypx.ec.common.to.es.SkuEsModel;
import com.ypx.ec.common.to.es.SkuHasStockVo;
import com.ypx.ec.common.utils.R;
import com.ypx.ec.product.entity.*;
import com.ypx.ec.product.feign.CouponFeignService;
import com.ypx.ec.product.feign.EsSearchService;
import com.ypx.ec.product.feign.WareFeignService;
import com.ypx.ec.product.service.*;
import com.ypx.ec.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ypx.ec.common.utils.PageUtils;
import com.ypx.ec.common.utils.Query;

import com.ypx.ec.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    EsSearchService esSearchService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void save(SpuSaveVo spuSaveVo) {

        //保存spu基本信息
       SpuInfoEntity spuInfoEntity= this.saveBase(spuSaveVo);

        //保存描述图片
        this.saveSpuInfoDesc(spuSaveVo,spuInfoEntity.getId());
        //保存图片列表
        this.saveSpuInfoImages(spuSaveVo,spuInfoEntity.getId());
        this.saveSpuInfoAttr(spuSaveVo,spuInfoEntity.getId());
        this.saveSkuInfo(spuSaveVo,spuInfoEntity.getId());
        this.saveSpuInfoBounds(spuSaveVo,spuInfoEntity.getId());
    }




    public SpuInfoEntity saveBase(SpuSaveVo spuSaveVo) {
        SpuInfoEntity spuInfoEntity=new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);
        return spuInfoEntity;
    }
    public void saveSpuInfoDesc(SpuSaveVo spuSaveVo, Long spuBaseId){
        SpuInfoDescEntity entity=new SpuInfoDescEntity();
        entity.setDecript(String.join(",",spuSaveVo.getDecript()));
        entity.setSpuId(spuBaseId);
        spuInfoDescService.save(entity);
    }
    public void saveSpuInfoImages(SpuSaveVo spuSaveVo, Long spuBaseId){
        if(spuSaveVo.getImages().size()==0 || spuSaveVo.getImages()==null){
            return;
        }
        List<SpuImagesEntity> list=spuSaveVo.getImages().stream().map((ele)->{
            SpuImagesEntity entity=new SpuImagesEntity();
            entity.setImgUrl(ele);
            entity.setSpuId(spuBaseId);
            return entity;
        }).filter((entity->{
            return !StringUtils.isEmpty(entity.getImgUrl());
        })).collect(Collectors.toList());

        spuImagesService.saveBatch(list);
    }
    public void saveSpuInfoAttr(SpuSaveVo spuSaveVo, Long spuBaseId){
        List<BaseAttrs> baseAttrs=spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> list=baseAttrs.stream().map((ele)->{
            ProductAttrValueEntity entity=new ProductAttrValueEntity();
            String attrName=attrService.getById(ele.getAttrId()).getAttrName();
            entity.setAttrName(attrName);
            entity.setAttrValue(ele.getAttrValues());
            entity.setAttrId(ele.getAttrId());
            entity.setQuickShow(ele.getShowDesc());
            entity.setSpuId(spuBaseId);
            return entity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(list);
    }
    public void saveSkuInfo(SpuSaveVo spuSaveVo, Long spuBaseId){

        List<Skus> skus = spuSaveVo.getSkus();
        if(skus.size()==0 || skus==null){
            return;
        }

        for (Skus sku : skus) {


            List<Images> images=sku.getImages();
            String defaultImg="";
            for (int i = 0; i < images.size(); i++) {
                Images image=images.get(i);
                if(image.getDefaultImg().equals(1)){
                    defaultImg=image.getImgUrl();
                }
            }

            SkuInfoEntity entity=new SkuInfoEntity();
            BeanUtils.copyProperties(sku,entity);
            entity.setBrandId(spuSaveVo.getBrandId());
            entity.setCatalogId(spuSaveVo.getCatalogId());
            entity.setSaleCount(0L);
            entity.setSpuId(spuBaseId);
            entity.setSkuDefaultImg(defaultImg);
            skuInfoService.save(entity);

            Long skuId=entity.getSkuId();
            List<SkuImagesEntity> skuImagesEntities=images.stream().map((image)->{
                SkuImagesEntity skuImagesEntity=new SkuImagesEntity();
                BeanUtils.copyProperties(image,skuImagesEntity);
                skuImagesEntity.setSkuId(skuId);
                return skuImagesEntity;
            }).filter(ele->{
                return !StringUtils.isEmpty(ele.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);


            List<Attr> attrEntities=sku.getAttr();
            List<SkuSaleAttrValueEntity> attrValueEntities=attrEntities.stream().map((attr)->{
                SkuSaleAttrValueEntity skuSaleAttrValueEntity=new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(attrValueEntities);



            SkuReductionTo skuReductionTo=new SkuReductionTo();
            BeanUtils.copyProperties(sku,skuReductionTo);
            skuReductionTo.setSkuId(skuId);
            couponFeignService.saveInfo(skuReductionTo);

        }


    }
    public void saveSpuInfoBounds(SpuSaveVo spuSaveVo, Long spuBaseId){
        Bounds bounds=spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo=new SpuBoundsTo();
        spuBoundsTo.setSpuId(spuBaseId);
        spuBoundsTo.setBuyBounds(bounds.getBuyBounds());
        spuBoundsTo.setGrowBounds(bounds.getGrowBounds());
        couponFeignService.save(spuBoundsTo);
    }

    @Override
    public void up(Long spuId) {
        List<SkuInfoEntity> skus=skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id",spuId));
        Map<Long, Boolean> stockMap = null;
        try {
            List<Long> longList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            TypeReference<List<SkuHasStockVo>> listTypeReference =new TypeReference<List<SkuHasStockVo>>(){

            };
            List<SkuHasStockVo> skuHasStocks = wareFeignService.getSkuHasStock(longList).getData(listTypeReference);
            stockMap = skuHasStocks.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        }catch (Exception e){
            log.error("远程调用库存服务失败,原因{}",e);
        }
        Map<Long, Boolean> finalStockMap=stockMap;

        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = productAttrValueEntities.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchIds=attrService.selectSearchAttrIds(attrIds);
        Set<Long> ids = new HashSet<>(searchIds);
        List<SkuEsModel.Attr> searchAttrs = productAttrValueEntities.stream().filter(entity -> {
            return ids.contains(entity.getAttrId());
        }).map(entity -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(entity, attr);
            return attr;
        }).collect(Collectors.toList());
        List<SkuEsModel> collect = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            skuEsModel.setHotScore(0L);

            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setHasStock(finalStockMap == null ? false : finalStockMap.get(sku.getSkuId()));
            skuEsModel.setAttrs(searchAttrs);
            return skuEsModel;
        }).collect(Collectors.toList());

        R r = esSearchService.productStatusUp(collect);

        if (r.getCode()==0){
            this.baseMapper.upSpuStatus(spuId, ProductConstant.SPU_Enum.SPU_UP.getCode());
        }else {
            log.error("商品远程es保存失败");
        }



    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }


}